package job.manager.db.sb;

import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import job.manager.db.dao.UserDAO;
import job.manager.db.dao.UserGroupsDAO;
import job.manager.db.ec.UserGroupsEB;
import job.manager.db.ec.UsersEB;
import job.manager.db.ex.UserNotFoundException;

/**
 *  SessionBean is the top layer and the main access point for handling the communcation
 *  from other modules to the database.
 *  This Bean is handling all the user requests.
 *
 */
@Stateless
public class UserBean implements UserRemote, UserLocal {

    @PersistenceContext
    private EntityManager em;

    private UserDAO udao;
    private UserGroupsDAO ugdao;

    public UserBean() {
        this.udao = new UserDAO(em);
        this.ugdao = new UserGroupsDAO(em);
    }

    public boolean authenticateUser(int userId, String url) {
        return true;
    }
    public boolean authenticateUser(UsersEB user, String url) {
        return this.authenticateUser(user.getId(), url);
    }

    public UsersEB login(String username, String password) throws UserNotFoundException
    {
        UserDAO udao = new UserDAO(this.em);
        UsersEB u = null;
        try {
            u = udao.getUser(username,password);
        }catch(NoResultException ex) {
            throw new UserNotFoundException("User and Password missmatch");
        }
        return u;
    }

    public int createUser(UsersEB user){
        return new UserDAO(this.em).insert(user);
    }

    public int updateUser(UsersEB user) {
        return new UserDAO(this.em).update(user);
    }

    public int deleteUser(UsersEB user) {
        return new UserDAO(this.em).delete(user);
    }
    public int deleteUser(Integer pk) {
        return this.deleteUser(em.find(UsersEB.class,pk));
    }

    public Collection<UsersEB> getAllUsers() {
        return new UserDAO(this.em).getAllUsers();
    }

    public Collection<UserGroupsEB> getUserGroups() {
        return new UserGroupsDAO(this.em).getAllUserGroups();
    }

    public UserGroupsEB getUserGroup(int userGroupId) {
        return new UserGroupsDAO(this.em).getUserGroupByPk(userGroupId);
    }

    public UsersEB findUser(String userName) {
        return new UserDAO(this.em).getUserByUsername(userName);
    }
}
